/*
 * Powered By [rapid-framework]
 * Web Site: http://www.rapid-framework.org.cn
 * Google Code: http://code.google.com/p/rapid-framework/
 * Since 2008 - 2013
 */


package com.smg.community.controller;


import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javacommon.base.BaseRestSpringController;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import cn.org.rapid_framework.page.Page;

import com.smg.community.model.City;
import com.smg.community.model.CrmUser;
import com.smg.community.model.ExtJsPageData;
import com.smg.community.model.SmgKeyword;
import com.smg.community.service.CityManager;
import com.smg.community.vo.query.SmgKeywordQuery;

/**
 * @author badqiu email:badqiu(a)gmail.com
 * @version 1.0
 * @since 1.0
 */

@Controller
@RequestMapping("/smgkeyword")
public class SmgKeywordController extends BaseRestSpringController<SmgKeyword,java.lang.Integer>{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	

	@RequestMapping(value="/list")
	public String  list(HttpServletRequest request,ModelMap model){
		CrmUser loginUser = getLoginUser(request);
		String userCityNos = loginUser.getCityNo();
		if  ( userCityNos == null ||  userCityNos.length() == 0 ){
			model.addAttribute("message","用户不拥有任何城市");
			return "/common/error";
		}
		List<City> cityList = CityManager.getCityListByUserCityNos(userCityNos);
		model.addAttribute("cityList",cityList);
		userCityNos = userCityNos.substring(0);
		userCityNos = userCityNos.substring(1,userCityNos.length()-1);
		model.addAttribute("userCityNos",userCityNos);
		return "/keyword/list";
	}
	
	@RequestMapping(value="/getpagedata")
	public    @ResponseBody ExtJsPageData<SmgKeyword> getListData(SmgKeywordQuery query){
		Page<SmgKeyword> page   = smgKeywordManager.findPage(query);
		return transToExtJsPageData(page.getResult(),page.getTotalCount());
	}
	@RequestMapping(value="/update")
	public    @ResponseBody  Map<String,String> update(@RequestParam String ids,@RequestParam String isValid){
		
		smgKeywordManager.updateIsValid(ids,isValid);
		return writeSuccessMessage();
	}
	@RequestMapping(value="/importbyfile")
	public    @ResponseBody  Map<String,String> importByFile(HttpServletRequest request,@RequestParam String keyWords){
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest
				.getFile("filename");
		String desc = "";
		int totalCount = 0;
		int successCount  = 0;
		int repeatCount = 0;
		CrmUser loginUser = getLoginUser(request);
		try {
			if ( file.getSize()>0 && file.getOriginalFilename().indexOf("txt")!=-1){
				FileItem fileItem = file.getFileItem();
				String text;
				HashSet<String> set = new HashSet<String>();
				try {
					//FileInputStream fr = new FileInputStream(file);
					BufferedReader br = new BufferedReader(new InputStreamReader(fileItem.getInputStream(),"GBK"));
					while((text = br.readLine()) != null){
						totalCount ++ ;
						text = text.trim();
						if(text.equals("")){
							continue;
						}
						successCount ++ ;
						set.add(text);
					}
					br.close();
					//fr.close();
				} catch (Exception ex) {
					ex.printStackTrace();
				}
				for(String keyword:set){
					SmgKeyword smgKeyword = new SmgKeyword();
					smgKeyword.setCreateDate(new Date());
					smgKeyword.setCreateUser(loginUser.getUserName());
					smgKeyword.setKeyword(keyword);
					smgKeyword.setIsValid(1);
					if  ( smgKeywordManager.getByKeyword(keyword) == null){
						smgKeywordManager.save(smgKeyword);
						successCount ++ ;
					}else{
						repeatCount ++ ;
					}
				}
				desc = desc +"上传的文件总共包含 "+ totalCount+" 个关键字,导入成功 "+successCount+" 个关键字 ";
			}
			int  inputCount = 0 ;
			keyWords = keyWords.replaceAll("，", ",");
			keyWords = keyWords.trim();
			String[] keyWordArray = keyWords.split(",");
			if ( keyWordArray.length > 0 ) {
				for(String keyword:keyWordArray){
					if ( keyword.equals("")){
						continue;
					}
					SmgKeyword smgKeyword = new SmgKeyword();
					smgKeyword.setCreateDate(new Date());
					smgKeyword.setCreateUser(loginUser.getUserName());
					smgKeyword.setKeyword(keyword);
					smgKeyword.setIsValid(1);
					if  ( smgKeywordManager.getByKeyword(keyword) == null){
						smgKeywordManager.save(smgKeyword);
						inputCount ++ ;
					}else{
						repeatCount ++;
					}
				}
				if (inputCount > 0){
					desc =  desc+" 成功导入手动输入的"+inputCount+"个关键字";
				}
			}
			if ( repeatCount > 0){
				desc =  desc+" 其中有  "+repeatCount+" 个关键字重复";
			}
		}catch(Exception e){
			e.printStackTrace();
			return  writeErrorMessage();
		}
		return writeSuccessMessage(desc);
	}

	
}

